<?php
namespace Yjsh\Controller;
use Common\Controller\AppframeController;
use Think\Cache\Driver\Redis;
use Yjsh\Model\CommunityStoreLimitModel;
use Yjsh\Model\CommunityStoreOrderManagerModel;
use Yjsh\Model\CommunityStoreOrderModel;
use Yjsh\Model\PayCallBackUrlModel;

/**
 * 首页
 */
class CommunitystoreController extends AppframeController {

    private $page_size;
    private $shoppingcart_type;
    private $switch;
    private $lowest_price;
    private $service_fee;
    private $service_fee_start;
    private $no_service_fee_category;

    function _initialize() {
        parent::_initialize();
        $this->page_size                = 10;
        $this->shoppingcart_type        = 3;                // 购物车类型 - 铺货商品
        $this->lowest_price             = 99;               // 起送价
        $this->service_fee_start        = 9999999999;       // 代采费门槛 - 单笔订单，超过门槛，免收代采费
        $this->service_fee              = 1;                // 代采费
        $this->no_service_fee_category  = [15];             // 不需要代采费的商品分类
        $this->switch                   = true;             // 开关
    }

    // 铺货规则
    public function get_cs_rule()
    {
        $rules = array(
            '1. 铺货规则：',
            '① 每种商品都可以选择支付方式，现金支付(即微信支付)和"信用额"支付',
            '② 每种商品都有"回调天数"限制，"回调天数"内，可申请回调，超出"回调天数"，则认为以售出',
            '③ "回调天数"内，可分批支付商品，以回涨"信用额"用于下次铺货',
            '④ "信用额"周期性调整，商品回调率低的，"信用额"会上涨，反之下调',
            '⑤ 奖励金采取主动领取的方式，发放到用户余额中',
            '2. 退货规则',
            '① 未发货的订单，支持退货退款，按支付方式原路退还',
            '② 只有使用"信用额"支付的商品，可享受商品回调服务',
        );
        $this->ajaxReturn(['status' => 1, 'rules' => $rules]);
    }

    // 获取用户铺货状态
    public function yxs_apply_cs()
    {
        $result     = array();
        $user_id    = I('get.user_id', 0);
        if ($user_id) {
            $Model      = M('community');
            $cs_info    = $Model->where(['head_uid' => $user_id])->find();
            if ($cs_info) {
                if ($cs_info['cs_status'] < 3) {
                    if ($cs_info['cs_status'] != 2) {
                        if ($cs_info['old_credit'] <= 0) {
                            // 新铺货团长
                            if (strtotime($cs_info['create_time']) + 30 * 24 * 3600 > time()) {
                                // 未满一个月
                                $credit     = 119;
                                $old_credit = 119;
                                $new_credit = 119;
                            } else {
                                // 超过一个月
                                $start_time     = date("Y-m-d H:i:s", time() - 30 * 24 * 3600);
                                $total_amount   = M('order')->where(['commu_id' => $cs_info['id'], 'status' => ['GT', 1], 'pay_time' => ['GT', $start_time]])->sum('price');
                                $credit         = $total_amount / 26 * 0.6;
                                $old_credit     = $credit;
                                $new_credit     = $credit;
                            }
                        } else {
                            // 之前曾经是铺货团长
                            $credit         = $cs_info['credit'];
                            $old_credit     = $cs_info['old_credit'];
                            $new_credit     = $cs_info['new_credit'];
                        }
                        $data = ['cs_status' => 2, 'type' => 2, 'credit' => $credit, 'old_credit' => $old_credit, 'new_credit' => $new_credit, 'cs_apply_time' => time()];
                        $Model->where(['head_uid' => $user_id])->save($data);
                    }
                    // 绑定自己团长
                    $ucModle    = M('user_community');
                    $bindCs     = $ucModle->where(['uid' => $user_id, 'status' => 1])->find();
                    if ($bindCs) {
                        if ($bindCs['cid'] != $cs_info['id']) {
                            $ucModle->where(['id' => $bindCs['id']])->save(['cid' => $cs_info['id']]);
                        }
                    } else {
                        $data = array('uid' => $user_id, 'cid' => $cs_info['id'], 'create_time' => date("Y-m-d H:i:s"), 'status' => 1);
                        $ucModle->add($data);
                    }
                    $result['status'] = 1;
                } else {
                    // 禁止铺货
                    $result['msg'] = '禁止铺货，请联系客服';
                }
            } else {
                $result['msg'] = '参数错误2';
            }
        } else {
            $result['msg'] = '参数错误1';
        }
        $this->ajaxReturn($result);
    }

    // 申请成为可铺货团长
    public function apply_cs_community()
    {
        $result     = array();
        $user_id    = I('get.user_id', 0);
        if ($user_id) {
            $community  = M('community')->where(['head_uid' => $user_id])->find();
            if ($community) {
                if ($community['cs_status'] < 3) {
                    if ($community['cs_status'] == 0) {
                        M('community')->where(['head_uid' => $user_id])->save(['cs_status' => 1, 'cs_apply_time' => time()]);
                        $result['status'] = 1;
                    } elseif ($community['cs_status'] == 1) {
                        $result['msg'] = '正在审核，请耐心等待';
                    } else {
                        $result['msg'] = '状态有误';
                    }
                } else {
                    $result['msg'] = '铺货功能已禁用，请联系客服';
                }
            } else {
                $result['msg'] = '请先申请成为团长';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 获取可铺货商品类型列表
    public function product_category()
    {
        $result = array('status' => 1);
        $where  = array('p.status' => 1, 'p.is_cs' => 1);
        $cids   = M('product')
            ->alias("p")
            ->join("__PRODUCT_CATEGORY__ pg on pg.pid = p.id")
            ->field("DISTINCT(pg.cid)")
            ->where($where)
            ->select();

        $lists = [];
        if ($cids) {
            $lists  = M('category')->where(['id' => ['in', array_column($cids, 'cid')]])->select();
        }
        $result['lists'] = $lists;
        $this->ajaxReturn($result);
    }

    // 获取某个类型的可铺货商品
    public function product_list()
    {
        $result     = array();
        $c_id       = I('get.c_id', 0);
        $user_id    = I('get.user_id', 0);
        if ($c_id) {
            $conf   = $this->get_config();
            $where  = array('p.status' => 1, 'p.is_cs' => 1, 'pg.cid' => $c_id);
            $count  = M('product')
                ->alias("p")
                ->join("__PRODUCT_CATEGORY__ pg on pg.pid = p.id")
                ->join("__SHOPPINGCART__ sc on sc.pid = p.id and sc.uid = $user_id and sc.type = " . $this->shoppingcart_type, 'left')
                ->where($where)
                ->count();
            $page   = $this->page($count, $this->page_size);
            $lists  = M('product')
                ->alias("p")
                ->join("__PRODUCT_CATEGORY__ pg on pg.pid = p.id")
                ->join("__SHOPPINGCART__ sc on sc.pid = p.id and sc.uid = $user_id and sc.type = " . $this->shoppingcart_type, 'left')
                ->join("__TAG__ t on p.tag = t.id", 'left')
                ->where($where)
                ->limit($page->firstRow , $page->listRows)
                ->field('p.*, t.name as tag_name, t.pic as t_pic, sc.num as cart_num')
                ->order('p.sort desc, p.id desc')
                ->select();
            $stocks = $this->get_product_stocks(array_column($lists, 'id'));
            foreach ($lists as $k => $v) {
                $v['prePic']            = $conf['img_base_url'] . $v['pre_pic'];
                $v['tag']               = $v['tag'] > 0 ? $conf['img_base_url'] . $v['t_pic'] : '';
                $v['cs_max_return_num'] = (int)$v['cs_max_return_num']; // 方便前端显示
                $v['stock']             = $stocks[$v['id']];
                $lists[$k]              = $v;
            }

            $result['status']   = 1;
            $result['pages']    = ceil($count / $this->page_size);
            $result['lists']    = $lists;
        } else {
            $result['msg'] = " 参数错误";
        }
        $this->ajaxReturn($result);
    }

    // 我的铺货购物车
    public function shoppingcart()
    {
        $result     = array();
        $user_id    = I('get.user_id', 0);
        if ($user_id) {
            // 获取购物车列表，不分页
            $conf   = $this->get_config();
            $where  = [
                's.uid'     => $user_id,
                'p.status'  => 1,
                'p.is_cs'   => 1,
                's.type'    => $this->shoppingcart_type,
            ];
            $count  = M("shoppingcart")
                ->alias('s')
                ->join("__PRODUCT__ p on p.id = s.pid")
                ->where($where)
                ->count();
            $lists  = M("shoppingcart")
                ->alias('s')
                ->join("__PRODUCT__ p on p.id = s.pid")
                ->join("(select * from t_community_store_limit where id IN (SELECT MAX(id) as id FROM t_community_store_limit WHERE community_user_id = " . $user_id . " GROUP BY p_id)) csl on csl.p_id = s.pid", 'left')
                ->where($where)
                ->limit(0)
                ->field("p.*, s.id as cart_id, s.num as cart_num, csl.new_guard_num as guard_num_limit, s.sel, (SELECT GROUP_CONCAT(cid) as c_ids FROM t_product_category WHERE pid = s.pid) as category_ids")
                ->select();

            foreach ($lists as $k => $v) {
                // 判断是否需要代采费
                $category_ids   = explode(',', $v['category_ids']);
                $service_pro    = 1;
                foreach ($category_ids as $c_id) {
                    if (in_array($c_id, $this->no_service_fee_category)) {
                        $service_pro = 0;
                        break;
                    }
                }
                $v['service_pro']   = $service_pro;
                $v['prePic']        = $conf['img_base_url'] . $v['pre_pic'];
                $v['guard_num']     = min($v['cs_max_return_num'], $v['guard_num_limit'] ?: $v['cs_max_return_num']); // 最高可担保份数
                $v['sel']           = (bool)($v['sel']); // 是否勾选
                $v['is_guard']      = false; // 是否选定了信用额支付
                $lists[$k]          = $v;
            }

            $result['status']               = 1;
            $result['pages']                = 1;
            $result['count']                = $count;
            $result['lists']                = $lists;
            $result['lowest_price']         = $this->lowest_price;
            $result['service_fee_start']    = $this->service_fee_start;
            $result['service_fee']          = $this->service_fee;
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 加入购物车
    public function add_shoppingcart()
    {
        $user_id    = I('get.user_id', 0);
        $p_id       = I('get.p_id', 0);
        $num        = I('get.num', 0);
        $sel        = I('get.sel', 1);
        $has_data   = M('shoppingcart')->where(['uid' => $user_id, 'pid' => $p_id, 'type' => $this->shoppingcart_type])->find();
        if ($has_data) {
            if ($num <= 0) {
                M('shoppingcart')->where(['id' => $has_data['id']])->delete();
            } else {
                M('shoppingcart')->where(['id' => $has_data['id']])->save(['num' => $num, 'sel' => $sel]);
            }
        } else {
            $data = array(
                'uid'   => $user_id,
                'pid'   => $p_id,
                'num'   => $num,
                'type'  => $this->shoppingcart_type,
                'sel'   => $sel,
            );
            M('shoppingcart')->add($data);
        }
        $where  = [
            's.uid'     => $user_id,
            'p.status'  => 1,
            'p.is_cs'   => 1,
            's.type'    => $this->shoppingcart_type,
        ];
        $total_count = M("shoppingcart")
            ->alias('s')
            ->join("__PRODUCT__ p on p.id = s.pid")
            ->where($where)
            ->count();
        $this->ajaxReturn(['status' => 1, 'total_count' => $total_count]);
    }

    // 购物车 全选 / 全不选
    public function shoppingcart_sel_all()
    {
        $user_id    = I('get.user_id', 0);
        $type       = I('get.type', 0);
        if ($user_id) {
            $sel    = $type ? 1 : 0;
            $where  = ['uid' => $user_id, 'type' => $this->shoppingcart_type];
            M('shoppingcart')->where($where)->save(['sel' => $sel]);
        }
        $this->ajaxReturn(['status' => 1]);
    }

    // 生成订单
    public function create_order()
    {
        $user_id    = I('get.user_id', 0);
        $buy_info   = $_POST['buy_info'];
        $result     = array();
        if ($user_id && $buy_info && $this->switch) {
            // 检查是否有铺货的资格
            $community  = M('community')->where(['head_uid' => $user_id, 'cs_status' => 2])->find();
            if ($community) {
                // 检查有无过期未支付的商品
                $expire_lists = M('community_store_order')->where(['community_user_id' => $user_id, 'status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_WAIT_PAY])->find();
                if ($expire_lists) {
                    $result['msg'] = '还有超时未结算的订单';
                } else {
                    $buy_info   = json_decode($buy_info, true); // buy_info:[{"cart_id":11000,"is_credit":1},{"cart_id":购物车id,"is_credit":是否信用额支付}]
                    $pay_detail = array('total' => 0, 'credit' => 0, 'need_pay' => 0);
                    $credit     = $community['credit'];
                    $prod_lists = M('shoppingcart')
                        ->alias('s')
                        ->join("__PRODUCT__ p on s.pid = p.id")
                        ->where(['s.id' => ['in', array_column($buy_info, 'cart_id')], 's.uid' => $user_id, 's.type' => $this->shoppingcart_type])
                        ->field("p.*, s.id as p_cart_id, s.num as cart_num")
                        ->select();
                    $buy_info   = array_column($buy_info, NULL, 'cart_id');
                    $prod_lists = array_column($prod_lists, NULL, 'p_cart_id');
                    if ($prod_lists && count($prod_lists) == count($buy_info)) {
                        foreach ($prod_lists as $k => $v) {
                            if (key_exists($k, $buy_info)) {
                                $v['is_credit']     = $buy_info[$k]['is_credit'];
                                $prod_lists[$k]     = $v;
                            }
                        }
                        $cslModel = D('Yjsh/CommunityStoreLimit');
                        foreach ($prod_lists as $k => $product) {
                            $product['total_num'] = $product['cart_num'];
                            if ($product['is_credit']) {// 使用信用额支付
                                // 确认信用额可支付商品数量
                                $csl_info = $cslModel->where(['community_user_id' => $user_id, 'p_id' => $product['id']])->order('created_at desc')->find();
                                if ($csl_info) {
                                    $product['product_num'] = min($product['cs_max_return_num'], $product['cart_num'], $csl_info['new_guard_num']);
                                } else {
                                    $product['product_num'] = min($product['cs_max_return_num'], $product['cart_num']);
                                }
                                $credit = $credit - $product['product_num'] * $product['sale_price'];
                            } else {
                                $product['product_num'] = 0;
                            }
                            if ($credit >= 0) {
                                // 支付明细
                                $pay_detail['total']        = $pay_detail['total'] + $product['cart_num'] * $product['sale_price'];
                                $pay_detail['credit']       = $pay_detail['credit'] + $product['product_num'] * $product['sale_price'];
                                $pay_detail['need_pay']     = $pay_detail['need_pay'] + max(0, $product['cart_num'] - $product['product_num']) * $product['sale_price'];
                                // 记录
                                $prod_lists[$k] = $product;
                            } else {
                                $result['msg'] = '信用额不足~';
                                break;
                            }
                        }
                    } else {
                        $result['msg'] = '订单信息有误，请重新下单';
                    }
                    if (!isset($result['msg'])) {
                        // 判断起送价
                        if ($pay_detail['total'] < $this->lowest_price) {
                            $result['msg'] = "未到达起送价";
                        } else {
                            // 删除购物车数据
                            $cart_ids = array_column($buy_info, 'cart_id');
                            M('shoppingcart')->where(['id' => ['in', $cart_ids]])->delete();
                            // 插入铺货订单表
                            $cso_no         = get_inc_no('cso');
                            $insert_array   = array();
                            foreach ($prod_lists as $k => $v) {
                                $data = array(
                                    'community_user_id'    => $user_id,
                                    'pay_call_back_url_id' => 0,
                                    'cso_no'               => $cso_no,
                                    'p_id'                 => $v['id'],
                                    'order_id'             => 0,
                                    'total_num'            => $v['cart_num'],
                                    'protect_num'          => $v['product_num'],
                                    'return_num'           => 0,
                                    'part_pay_num'         => 0,
                                    'other_num'            => max(0, $v['cart_num'] - $v['product_num']),
                                    'last_return_time'     => 0,
                                    'award'                => 0,
                                    'award_status'         => CommunityStoreOrderModel::CSG_ORDER_AWARD_STATUS_WAIT_RECEIVE,
                                    'status'               => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_PAY,
                                    'created_at'           => time(),
                                    'finish_time'          => 0,
                                );
                                $insert_array[] = $data;
                            }
                            M('Community_store_order')->addAll($insert_array);
                            // 数据返回
                            $result['status']               = 1;
                            $result['cso_no']               = $cso_no;
                        }
                    }
                }
            } else {
                $result['msg'] = '未获得铺货资格';
            }
        } else {
            $result['msg'] = '参数错误1';
        }
        $this->ajaxReturn($result);
    }

    // 支付订单
    public function pay_order()
    {
        $cso_no     = I('get.cso_no', 0);
        $user_id    = I('get.user_id', 0);
        $result     = array();
        if ($cso_no && $user_id) {
            $community  = M('community')->where(['head_uid' => $user_id, 'cs_status' => 2])->find();
            if ($community) {
                $csoModel   = D('Yjsh/CommunityStoreOrder');
                $where      = ['cso.community_user_id' => $user_id, 'cso.status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_PAY, 'cso.cso_no' => $cso_no];
                $sg_num     = 0; // 需要代采费的商品总数
                $all_price  = 0; // 商品总价
                $credit     = $community['credit'];
                $buy_info   = []; // 减库存信息
                $has_pcb_id = false; // 该订单是否调起过支付（是否扣除过信用额）
                $old_pcb_id = 0; // 用于查询待支付的订单id
                $lists      = $csoModel
                    ->alias('cso')
                    ->join('__PRODUCT__ p on cso.p_id = p.id')
                    ->where($where)
                    ->limit(0)
                    ->field('cso.*, p.sale_price, p.cs_return_day, (SELECT GROUP_CONCAT(cid) as c_ids FROM t_product_category WHERE pid = cso.p_id) as category_ids')
                    ->select();
                foreach ($lists as $k => $v) {
                    $old_pcb_id     = $old_pcb_id ?: $v['pay_call_back_url_id'];
                    // 判断是否需要代采费
                    $category_ids   = explode(',', $v['category_ids']);
                    $service_pro    = 1;
                    foreach ($category_ids as $c_id) {
                        if (in_array($c_id, $this->no_service_fee_category)) {
                            $service_pro = 0;
                            break;
                        }
                    }
                    if ($service_pro) {
                        $sg_num     = $sg_num + $v['total_num'];
                    }
                    $buy_info[]     = array('p_id' => $v['p_id'], 'reduce_stock' => $v['total_num']);
                    $all_price      = $all_price + $v['total_num'] * $v['sale_price'];
                    $credit         = $credit - $v['protect_num'] * $v['sale_price'];
                    // 该订单是否调起过支付（是否扣除过信用额）
                    if ($v['pay_call_back_url_id'] > 0) {
                        $has_pcb_id = true;
                    }
                    if ($credit < 0) {
                        $result['msg'] = '信用额不足!';
                        break;
                    }
                }
                if (!isset($result['msg'])) {
                    // 判断起送价
                    if ($all_price < $this->lowest_price) {
                        $result['msg'] = "未到达起送价";
                    } else {
                        // 如果该笔订单，没有调起过支付，则扣除信用额
                        $re = true;
                        $total_sub_credit = max(0, $community['credit'] - $credit);
                        if (!$has_pcb_id && $total_sub_credit > 0) {
                            $re = $this->op_community_credit($user_id, $total_sub_credit, 'sub');
                        }
                        if ($re) {
                            // 线下支付
                            $refund_amount = $amount = round($sg_num * $this->service_fee, 2);
                            // 优化库存信息
                            $pay_call_back_url_id   = 0;
                            $result['order_id']     = 0;
                            if ($old_pcb_id) {
                                // 查找待支付的订单信息
                                $pay_call_back_data = M('pay_call_back_url')->where(['id' => $old_pcb_id, 'order_id' => ['GT', 0], 'created_at' => ['GT', time() - 30 * 60]])->find();
                                if ($pay_call_back_data) {
                                    $order_info = M('order')->where(['id' => $pay_call_back_data['order_id'], 'status' => 0])->find();
                                    if ($order_info) {
                                        // 如果能使用之前的订单表数据，前端就不用再调用支付的submit接口重新生成订单数据了
                                        $pay_call_back_url_id   = $old_pcb_id;
                                        $result['order_id']     = $order_info['id'];
                                    }
                                }
                            }
                            if (!$pay_call_back_url_id) {
                                // 生成支付回调数据
                                $pay_call_back_data = array(
                                    'user_id'       => $user_id,
                                    'order_id'      => 0,
                                    'amount'        => $amount,
                                    'refund_amount' => $refund_amount,
                                    'order_type'    => PayCallBackUrlModel::ORDER_TYPE_COMMUNITY_STORE,
                                    'can_refund'    => 1,
                                    'buy_info'      => json_encode($buy_info),
                                    'method'        => PayCallBackUrlModel::METHOD_TYPE_GET,
                                    'params'        => '',
                                    'created_at'    => time(),
                                );
                                $pay_call_back_url_id = M('pay_call_back_url')->add($pay_call_back_data);
                                $url = C('DOMAIN_NAME') . U('Yjsh/Communitystore/pay_call_back', ['pay_call_back_id' => $pay_call_back_url_id, 'user_id' => $user_id]);
                                M('pay_call_back_url')->where(['id' => $pay_call_back_url_id])->save(['url' => $url]);
                                // 更新订单数据
                                $csoModel->alias('cso')->where($where)->save(['pay_call_back_url_id' => $pay_call_back_url_id]);
                            }

                            // 数据返回
                            $result['status']               = 1;
                            $result['pay_call_back_url_id'] = $pay_call_back_url_id;
                            $result['need_pay']             = $amount;
                        } else {
                            $result['msg'] = '信用额不足~';
                        }
                    }
                }
            } else {
                $result['msg'] = '身份信息有误';
            }
        } else {
            $result['msg'] = '参数错误1';
        }
        $this->ajaxReturn($result);
    }

    // 支付成功回调
    public function pay_call_back()
    {
        $pay_call_back_id   = I('get.pay_call_back_id', 0);
        $order_id           = I('get.order_id', 0);
        $result             = array();
        if ($pay_call_back_id && $order_id) {
            // 修改订单状态
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $where      = ['cso.pay_call_back_url_id' => $pay_call_back_id, 'cso.status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_PAY];
            $task_key   = [];
            $lists      = $csoModel
                ->alias('cso')
                ->join('__PRODUCT__ p on cso.p_id = p.id')
                ->where($where)
                ->limit(0)
                ->field('cso.*, p.cs_return_day')
                ->select();
            foreach ($lists as $k => $v) {
                // 定时任务
                in_array($v['cs_return_day'], $task_key) ? $task_key : array_push($task_key, $v['cs_return_day']);
                // 获取最后回调时间
                $data = ['order_id' => $order_id, 'status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND];
                if ($v['protect_num'] > 0) {
                    $data['last_return_time'] = $this->calc_last_return_time($v['cs_return_day']);
                }
                $csoModel->where(['id' => $v['id']])->save($data);
            }
            // 设置定时任务， 周期性（一周）调整团长的信用额
            list($start, $end)  = get_week_start_end();
            $redis              = Redis::getinstance();
            $key                = $key    = 'call_back|http://' . C('DOMAIN_NAME') . U('Yjsh/Communitystore/task_cycle_change_credit', ['time' => $end]);
            $re                 = $redis->get($key);
            if (!$re) {
                $redis->set($key, 1, (int)($end - time()));
            }
            // 设置定时任务， 过了最后回调时间的订单，状态改成已结算未支付
            if ($task_key) {
                foreach ($task_key as $return_day) {
                    $key1   = 'call_back|http://' . C('DOMAIN_NAME') . U('Yjsh/Communitystore/task_check_expire_order', ['return_day' => $return_day]);
                    $re     = $redis->get($key1);
                    if (!$re) {
                        $last = $this->calc_last_return_time($return_day);
                        $redis->set($key1, 'pay_call_back_id=' . $pay_call_back_id . " order_id=" . $order_id, (int)($last - time()));
                    }
                }
            }
            // 返回成功
            $result['status'] = 1;
        } else {
            $result['msg'] = '参数错误';
        }
        // 记录错误log
        if (!isset($result['status'])) {
            writeFile("============ pay_call_back_error ============ start");
            writeFile("pay_call_back_id=" . $pay_call_back_id . " order_id=" . $order_id);
            writeFile($result);
            writeFile("============ pay_call_back_error ============ end");
        }
        $this->ajaxReturn($result);
    }

    // 取消订单
    public function cancel_order()
    {
        $cso_no     = I('get.cso_no', 0);
        $user_id    = I('get.user_id', 0);
        $result     = array();
        if ($cso_no && $user_id) {
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $where      = ['cso.cso_no' => $cso_no, 'cso.status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_PAY, 'cso.community_user_id' => $user_id];
            $add_credit = 0;
            $pcb_ids    = array();
            $lists      = $csoModel
                ->alias('cso')
                ->join('__PRODUCT__ p on cso.p_id = p.id')
                ->where($where)
                ->limit(0)
                ->field('cso.id, cso.protect_num, cso.part_pay_num, cso.pay_call_back_url_id, p.sale_price')
                ->select();
            foreach ($lists as $k => $v) {
                if ($v['pay_call_back_url_id'] > 0) {
                    // 操作order表数据
                    if (!in_array($v['pay_call_back_url_id'], $pcb_ids)) {
                        $pcb_ids[] = $v['pay_call_back_url_id'];
                    }
                    // 返还信用额
                    $add_credit = $add_credit + max(0, $v['protect_num'] - $v['part_pay_num']) * $v['sale_price'];
                }
            }
            // 通知订单中心，取消订单，处理库存
            if ($pcb_ids) {
                $order_ids = M('pay_call_back_url')->where(['id' => ['in', $pcb_ids], 'order_id' => ['GT', 0]])->field('order_id')->select();
                if ($order_ids) {
                    foreach ($order_ids as $v) {
                        // 正式服
                        $url    = "https://yjsh.rixins.cn/groupon/api/anon/cancelOrder?pwd=24680&id=" . $v['order_id'];
                        // 本地测试
//                        $url = "localhost:9009/api/anon/cancelOrder?pwd=24680&id=" . $v['order_id'];

                        $re = curl_requestion($url, [], 'GET', 60);
                        $re = json_decode($re['data'], true);
                        writeFile("cancel order order_id = " . $v['order_id']);
                        writeFile($re);
                    }
                }
            }
            // 设置订单信息
            $csoModel->alias('cso')->where($where)->save(['status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CANCELED]);
            // 返还信用额
            if ($add_credit > 0) {
                $this->op_community_credit($user_id, $add_credit, 'add');
            }
            // 数据返回
            $result['status'] = 1;
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 申请回调商品
    public function apply_return()
    {
        $result         = array();
        $user_id        = I('get.user_id', 0);
        $return_info    = $_POST['return_info']; // return_info:[{"cso_id":11000,"num":1},{"cso_id":铺货订单id,"num":回调数量}]
        if ($return_info && $user_id) {
            $return_info = json_decode($return_info, true);
            if ($return_info) {
                $csoModel       = D('Yjsh/CommunityStoreOrder');
                $amount         = 0; // 需支付金额
                $cso_lists      = $csoModel
                    ->alias('cso')
                    ->join('__PRODUCT__ p on cso.p_id = p.id')
                    ->where(['cso.id' => ['in', array_column($return_info, 'cso_id')]])
                    ->field('cso.*, p.cs_award_money, p.cs_max_return_num, p.name, p.sale_price')
                    ->select();
                $return_info    = array_column($return_info, NULL, 'cso_id');
                $cso_lists      = array_column($cso_lists, NULL, 'id');
                foreach ($cso_lists as $k => $v) {
                    if (key_exists($k, $return_info)) {
                        $v['num']       = $return_info[$k]['num'];
                        $cso_lists[$k]  = $v;
                    }
                }
                foreach ($cso_lists as $k => $order) {
                    if ($order['num'] <= 0) {
                        $result['msg'] = '参数错误1';
                        break;
                    }
                    if ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY && $order['return_num'] == 0 && $order['protect_num'] > 0) { // 判断当前状态是否可回调
                        if ($order['last_return_time'] > time()) { // 判断回调时间
                            if (max(0, $order['protect_num'] - $order['part_pay_num']) >= $order['num']) { // 判断回调数量
                                $order['amount']    = max(0, $order['protect_num'] - $order['part_pay_num'] - $order['num']) * $order['sale_price'];
                                $amount             = $amount + $order['amount'];
                                $cso_lists[$k]      = $order;
                            } else {
                                $result['msg'] = '<' . $order['name'] . '> 超出回调数量';
                                break;
                            }
                        } else {
                            $result['msg'] = '<' . $order['name'] . '> 超出回调时间';
                            break;
                        }
                    } else {
                        $result['msg'] = '<' . $order['name'] . '> 当前状态不可回调';
                        break;
                    }
                }
                if (!isset($result['msg'])) {
                    // 生成支付回调数据
                    $pay_call_back_data = array(
                        'user_id'       => $user_id,
                        'order_id'      => 0,
                        'amount'        => $amount,
                        'order_type'    => PayCallBackUrlModel::ORDER_TYPE_COMMUNITY_STORE_RETURN,
                        'can_refund'    => 0,
                        'buy_info'      => '',
                        'method'        => PayCallBackUrlModel::METHOD_TYPE_GET,
                        'params'        => '',
                        'created_at'    => time(),
                    );
                    $pay_call_back_url_id = M('pay_call_back_url')->add($pay_call_back_data);
                    $url = C('DOMAIN_NAME') . U('Yjsh/Communitystore/apply_return_pay_call_back', ['pay_call_back_id' => $pay_call_back_url_id, 'user_id' => $user_id]);
                    M('pay_call_back_url')->where(['id' => $pay_call_back_url_id])->save(['url' => $url]);
                    // 生成回调数据
                    $insert_array = array();
                    foreach ($cso_lists as $k => $v) {
                        $data = array(
                            'cso_id'                => $v['id'],
                            'pay_call_back_url_id'  => $pay_call_back_url_id,
                            'order_id'              => 0,
                            'type'                  => CommunityStoreOrderManagerModel::CSOM_TYPE_RETURN,
                            'num'                   => $v['num'],
                            'amount'                => $v['amount'],
                            'created_at'            => time(),
                        );
                        $insert_array[] = $data;
                    }
                    M('Community_store_order_manager')->addAll($insert_array);
                    // 数据返回
                    $result['status'] = 1;
                    $result['pay_call_back_url_id'] = $pay_call_back_url_id;
                }
            } else {
                $result['msg'] = '参数错误1';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 申请回调的支付回调
    public function apply_return_pay_call_back()
    {
        $pay_call_back_id   = I('get.pay_call_back_id', 0);
        $order_id           = I('get.order_id', 0);
        $user_id            = I('get.user_id', 0);
        $result             = array();
        if ($pay_call_back_id && $order_id && $user_id) {
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $csomModel  = D('Yjsh/CommunityStoreOrderManager');
            // 将回调订单数据，设置为已支付
            $where      = ['pay_call_back_url_id' => $pay_call_back_id, 'type' => CommunityStoreOrderManagerModel::CSOM_TYPE_RETURN];
            $re         = $csomModel->where($where)->save(['order_id' => $order_id]);
            if ($re) {
                // 修改铺户订单
                $csom_info  = $csomModel->where($where)->field('cso_id, num, amount')->select();
                $credit     = 0;
                $csr_arr    = array();
                $cso_lists  = $csoModel
                    ->alias('cso')
                    ->join('__PRODUCT__ p on cso.p_id = p.id')
                    ->where(['cso.id' => ['in', array_column($csom_info, 'cso_id')]])
                    ->field('cso.*, p.cs_award_money, p.cs_max_return_num')
                    ->select();
                $csom_info  = array_column($csom_info, NULL, 'cso_id');
                $cso_lists  = array_column($cso_lists, NULL, 'id');
                foreach ($cso_lists as $k => $v) {
                    if (key_exists($k, $csom_info)) {
                        $v['num']       = $csom_info[$k]['num'];
                        $v['amount']    = $csom_info[$k]['amount'];
                        $cso_lists[$k]  = $v;
                    }
                }
                foreach ($cso_lists as $k => $info) {
                    // 修改状态，回调数量，奖励金数量
                    $data = [
                        'status'        => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY,
                        'return_num'    => $info['num'],
                        'award'         => ($info['cs_award_money'] > 0 && $info['cs_max_return_num'] > 0) ? floor(($info['total_num'] - $info['num']) / $info['cs_max_return_num']) * $info['cs_award_money'] : 0,
                        'finish_time'   => time(),
                    ];
                    $csoModel->where(['id' => $info['id']])->save($data);
                    $credit = $credit + $info['amount'];
                    // 回调记录表数据
                    $csr_data = array(
                        'community_user_id'     => $user_id,
                        'cso_id'                => $info['id'],
                        'p_id'                  => $info['p_id'],
                        'apply_return_num'      => $info['num'],
                        'real_return_num'       => 0,
                        'receive_user_id'       => 0,
                        'receive_time'          => 0,
                        'status'                => 0,
                        'created_at'            => time(),
                    );
                    $csr_arr[] = $csr_data;
                    // 调整团长对该商品的可铺货数量
                    $this->change_cm_pro_limit($user_id, $info['p_id'], $info['cs_max_return_num'], $info['total_num'], $info['num']);
                }
                // 增加信用额
                if ($credit) {
                    $this->op_community_credit($user_id, $credit, 'add');
                }
                // 插入商品回调表数据
                if ($csr_arr) {
                    M('community_store_return')->addAll($csr_arr);
                }

                $result['status'] = 1;
            }  else {
                $result['msg'] = '修改回调订单失败';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        // 记录错误log
        if (!isset($result['status'])) {
            writeFile("============ apply_return_pay_call_back_error ============ start");
            writeFile("pay_call_back_id=" . $pay_call_back_id . " order_id=" . $order_id . "user_id=" . $user_id);
            writeFile($result);
            writeFile("============ apply_return_pay_call_back_error ============ end");
        }
        $this->ajaxReturn($result);
    }

    // 分批支付
    public function part_pay()
    {
        $result     = array();
        $user_id    = I('get.user_id', 0);
        $pay_info   = $_POST['pay_info']; // pay_info:[{"cso_id":11000,"num":1},{"cso_id":铺货订单id,"num":支付数量}]
        if ($pay_info && $user_id) {
            $pay_info   = json_decode($pay_info, true);
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $amount     = 0; // 需支付金额
            $cso_lists  = $csoModel
                ->alias('cso')
                ->join('__PRODUCT__ p on p.id = cso.p_id')
                ->where(['cso.id' => ['in', array_column($pay_info, 'cso_id')]])
                ->field('cso.*, p.sale_price, p.name')
                ->select();
            $pay_info   = array_column($pay_info, NULL, 'cso_id');
            $cso_lists  = array_column($cso_lists, NULL, 'id');
            foreach ($cso_lists as $k => $v) {
                if (key_exists($k, $pay_info)) {
                    $v['num']       = $pay_info[$k]['num'];
                    $cso_lists[$k]  = $v;
                }
            }
            foreach ($cso_lists as $k => $order) {
                if ($order['num'] <= 0) {
                    $result['msg'] = '参数错误1';
                    break;
                }
                if ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY && $order['return_num'] == 0) { // 判断当前状态是否可分批支付
                    if ($order['last_return_time'] > time()) { // 判断时间
                        if (max(0, $order['protect_num'] - $order['part_pay_num']) >= $order['num']) { // 判断数量
                            $order['amount']    = $order['num'] * $order['sale_price'];
                            $amount             = $amount + $order['amount'];
                            $cso_lists[$k]      = $order;
                        } else {
                            $result['msg'] = '<' . $order['name'] . '> 超出可支付数量';
                            break;
                        }
                    } else {
                        $result['msg'] = '<' . $order['name'] . '> 超出可支付时间';
                        break;
                    }
                } else {
                    $result['msg'] = '<' . $order['name'] . '> 当前状态不可支付';
                    break;
                }
            }
            if (!isset($result['msg'])) {
                // 生成支付回调数据
                $pay_call_back_data = array(
                    'user_id'       => $user_id,
                    'order_id'      => 0,
                    'amount'        => $amount,
                    'order_type'    => PayCallBackUrlModel::ORDER_TYPE_COMMUNITY_STORE_PART_PAY,
                    'can_refund'    => 0,
                    'buy_info'      => '',
                    'method'        => PayCallBackUrlModel::METHOD_TYPE_GET,
                    'params'        => '',
                    'created_at'    => time(),
                );
                $pay_call_back_url_id = M('pay_call_back_url')->add($pay_call_back_data);
                $url = C('DOMAIN_NAME') . U('Yjsh/Communitystore/part_pay_call_back', ['pay_call_back_id' => $pay_call_back_url_id, 'user_id' => $user_id]);
                M('pay_call_back_url')->where(['id' => $pay_call_back_url_id])->save(['url' => $url]);
                // 生成回调数据
                $insert_array = array();
                foreach ($cso_lists as $k => $v) {
                    $data = array(
                        'cso_id'                => $v['id'],
                        'pay_call_back_url_id'  => $pay_call_back_url_id,
                        'order_id'              => 0,
                        'type'                  => CommunityStoreOrderManagerModel::CSOM_TYPE_PART_PAY,
                        'num'                   => $v['num'],
                        'amount'                => $v['amount'],
                        'created_at'            => time(),
                    );
                    $insert_array[] = $data;
                }
                M('Community_store_order_manager')->addAll($insert_array);
                // 数据返回
                $result['status'] = 1;
                $result['pay_call_back_url_id'] = $pay_call_back_url_id;
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 分批支付的支付回调
    public function part_pay_call_back()
    {
        $pay_call_back_id   = I('get.pay_call_back_id', 0);
        $order_id           = I('get.order_id', 0);
        $user_id            = I('get.user_id', 0);
        $result             = array();
        if ($pay_call_back_id && $order_id && $user_id) {
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $csomModel  = D('Yjsh/CommunityStoreOrderManager');
            // 将分批支付订单数据，设置为已支付
            $where      = ['pay_call_back_url_id' => $pay_call_back_id, 'type' => CommunityStoreOrderManagerModel::CSOM_TYPE_PART_PAY];
            $re         = $csomModel->where($where)->save(['order_id' => $order_id]);
            if ($re) {
                // 查找数据
                $csom_info  = $csomModel->where($where)->field('cso_id, num, amount')->select();
                $credit     = 0;
                $cso_lists  = $csoModel
                    ->alias('cso')
                    ->join('__PRODUCT__ p on cso.p_id = p.id')
                    ->where(['cso.id' => ['in', array_column($csom_info, 'cso_id')]])
                    ->field('cso.*, p.cs_award_money, p.cs_max_return_num')
                    ->select();
                $csom_info  = array_column($csom_info, NULL, 'cso_id');
                $cso_lists  = array_column($cso_lists, NULL, 'id');
                foreach ($cso_lists as $k => $v) {
                    if (key_exists($k, $csom_info)) {
                        $v['num']       = $csom_info[$k]['num'];
                        $v['amount']    = $csom_info[$k]['amount'];
                        $cso_lists[$k]  = $v;
                    }
                }
                // 修改铺户订单
                foreach ($cso_lists as $k => $info) {
                    // 修改分批支付数量
                    $data = ['part_pay_num' => ['exp', 'part_pay_num + ' . $info['num']]];
                    if ($info['protect_num'] <= $info['part_pay_num'] + $info['num']) {
                        // 已全部支付
                        $data['status']         = CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY;
                        $data['finish_time']    = time();
                        $data['award']          = ($info['cs_award_money'] > 0 && $info['cs_max_return_num'] > 0) ? floor(($info['total_num'] - $info['return_num']) / $info['cs_max_return_num']) * $info['cs_award_money'] : 0;

                        // 调整团长对该商品的可铺货数量
                        $this->change_cm_pro_limit($user_id, $info['p_id'], $info['cs_max_return_num'], $info['total_num'], $info['return_num']);
                    }
                    $csoModel->where(['id' => $info['id']])->save($data);
                    $credit = $credit + $info['amount'];
                }
                // 增加信用额
                $this->op_community_credit($user_id, $credit, 'add');

                $result['status'] = 1;
            }  else {
                $result['msg'] = '修改分批支付订单失败';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        // 记录错误log
        if (!isset($result['status'])) {
            writeFile("============ part_pay_call_back_error ============ start");
            writeFile("pay_call_back_id=" . $pay_call_back_id . " order_id=" . $order_id . "user_id=" . $user_id);
            writeFile($result);
            writeFile("============ part_pay_call_back_error ============ end");
        }
        $this->ajaxReturn($result);
    }

    // 信用额支付，过回调时间，支付
    // 订单（信用额支付）已结算，过了最后回调时间，但未支付，获取单个商品信息，显示支付按钮
    public function expire_pay()
    {
        $cso_id     = I('get.cso_id', 0);
        $user_id    = I('get.user_id', 0);
        $result     = array();
        if ($cso_id && $user_id) {
            $csoModel = D('Yjsh/CommunityStoreOrder');
            $order    = $csoModel
                ->alias('cso')
                ->join('__PRODUCT__ p on p.id = cso.p_id')
                ->where(['cso.id' => $cso_id])
                ->field('cso.*, p.sale_price')
                ->find();
            if ($order) {
                if ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_WAIT_PAY && $order['return_num'] == 0 && $order['protect_num'] > $order['part_pay_num']) { // 判断当前状态是否可支付
                    if ($order['last_return_time'] < time()) { // 判断时间
                        // 生成支付回调数据
                        $pay_call_back_data = array(
                            'user_id'       => $user_id,
                            'order_id'      => 0,
                            'amount'        => max(0, $order['protect_num'] - $order['part_pay_num']) * $order['sale_price'],
                            'order_type'    => PayCallBackUrlModel::ORDER_TYPE_COMMUNITY_STORE_EXPIRE_PAY,
                            'can_refund'    => 0,
                            'buy_info'      => '',
                            'method'        => PayCallBackUrlModel::METHOD_TYPE_GET,
                            'params'        => '',
                            'created_at'    => time(),
                        );
                        $pay_call_back_url_id = M('pay_call_back_url')->add($pay_call_back_data);
                        $url = C('DOMAIN_NAME') . U('Yjsh/Communitystore/expire_pay_call_back', ['pay_call_back_id' => $pay_call_back_url_id, 'user_id' => $user_id]);
                        M('pay_call_back_url')->where(['id' => $pay_call_back_url_id])->save(['url' => $url]);
                        // 生成回调数据
                        $data = array(
                            'cso_id'                => $cso_id,
                            'pay_call_back_url_id'  => $pay_call_back_url_id,
                            'order_id'              => 0,
                            'type'                  => CommunityStoreOrderManagerModel::CSOM_TYPE_EXPIRE_PAY,
                            'num'                   => max(0, $order['protect_num'] - $order['part_pay_num']),
                            'amount'                => max(0, $order['protect_num'] - $order['part_pay_num']) * $order['sale_price'],
                            'created_at'            => time(),
                        );
                        M('Community_store_order_manager')->add($data);
                        // 数据返回
                        $result['status'] = 1;
                        $result['pay_call_back_url_id'] = $pay_call_back_url_id;

                    } else {
                        $result['msg'] = '未超时，可分批支付';
                    }
                } else {
                    $result['msg'] = '可分批支付或申请回调';
                }
            } else {
                $result['msg'] = '订单信息有误';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 过期支付的支付回调
    public function expire_pay_call_back()
    {
        $pay_call_back_id   = I('get.pay_call_back_id', 0);
        $order_id           = I('get.order_id', 0);
        $user_id            = I('get.user_id', 0);
        $result             = array();
        if ($pay_call_back_id && $order_id && $user_id) {
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $csomModel  = D('Yjsh/CommunityStoreOrderManager');
            // 将过期支付订单数据，设置为已支付
            $where      = ['pay_call_back_url_id' => $pay_call_back_id, 'type' => CommunityStoreOrderManagerModel::CSOM_TYPE_EXPIRE_PAY];
            $re         = $csomModel->where($where)->save(['order_id' => $order_id]);
            if ($re) {
                // 修改铺户订单
                $csom_info  = $csomModel->where($where)->field('cso_id, num, amount')->select();
                $credit     = 0;
                foreach ($csom_info as $k => $v) {
                    $info = $csoModel
                        ->alias('cso')
                        ->join('__PRODUCT__ p on cso.p_id = p.id')
                        ->where(['cso.id' => $v['cso_id']])
                        ->field('cso.*, p.cs_award_money, p.cs_max_return_num')
                        ->find();
                    if ($info) {
                        // 修改状态，回调数量，奖励金数量
                        $data = [
                            'status'        => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY,
                            'award'         => ($info['cs_award_money'] > 0 && $info['cs_max_return_num'] > 0) ? floor(($info['total_num'] - $info['return_num']) / $info['cs_max_return_num']) * $info['cs_award_money'] : 0,
                            'finish_time'   => time(),
                        ];
                        $csoModel->where(['id' => $v['cso_id']])->save($data);
                        $credit = $credit + $v['amount'];
                        // 调整团长对该商品的可铺货数量
                        $this->change_cm_pro_limit($user_id, $info['p_id'], $info['cs_max_return_num'], $info['total_num'], $info['return_num']);
                    }
                }
                // 增加信用额
                $this->op_community_credit($user_id, $credit, 'add');

                $result['status'] = 1;
            }  else {
                $result['msg'] = '修改过期支付订单失败';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        // 记录错误log
        if (!isset($result['status'])) {
            writeFile("============ expire_pay_call_back_error ============ start");
            writeFile("pay_call_back_id=" . $pay_call_back_id . " order_id=" . $order_id . "user_id=" . $user_id);
            writeFile($result);
            writeFile("============ expire_pay_call_back_error ============ end");
        }
        $this->ajaxReturn($result);
    }


    // 退款
    public function refund_order()
    {
        $cso_no     = I('get.cso_no', 0);
        $user_id    = I('get.user_id', 0);
        $result     = array();
        if ($cso_no && $user_id) {
            $conf           = $this->get_config();
            $csoModel       = D('Yjsh/CommunityStoreOrder');
            $where          = [
                'cso.community_user_id' => $user_id,
                'cso.order_id'          => ['GT', 0],
                'cso.status'            => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND,
                'cso.cso_no'            => $cso_no,
                'cso.created_at'        => ['LT', strtotime(date("Y-m-d " . $conf ? $conf['group_end_time'] : "23:00:00"))],
                'cso.created_at'        => ['GT', strtotime(date("Y-m-d"))]
            ];
            $order_ids      = array();
            $order_lists    = $csoModel
                ->alias('cso')
                ->join('__PRODUCT__ p on p.id = cso.p_id')
                ->where($where)
                ->limit(0)
                ->field('cso.id, cso.p_id, cso.protect_num, cso.part_pay_num, cso.pay_call_back_url_id, p.sale_price, cso.order_id')
                ->select();
            foreach ($order_lists as $v) {
                if (!in_array($v['order_id'], $order_ids)) {
                    $order_ids[] = $v['order_id'];
                }
            }
            if ($order_ids) {
                $log_key = "======= community_store  refund_order cso_no = $cso_no user_id = $user_id  ======= ";
                writeFile($log_key . "start");
                $access_token = get_yjsh_access_token();
                if ($access_token) {
                    // 正式服
                    $url    = "https://yjsh.rixins.cn/admin/api/service/batchRefund";
                    // 本地测试
//                    $url    = "localhost:9010/api/service/batchRefund";

                    $data   = ['ids' => implode(',', $order_ids)];
                    $re     = curl_requestion($url, $data, 'POST', 60, ['access_token:' . $access_token]);
                    writeFile($re);
                    if ($re['status']) {
                        $re = json_decode($re['data'], true);
                        if ($re['code'] == 200 && !$re['data']) {
                            // 返还信用额
                            $add_credit = 0;
                            foreach ($order_lists as $k => $v) {
                                if ($v['pay_call_back_url_id'] > 0) {
                                    // 返还信用额
                                    $add_credit = $add_credit + max(0, $v['protect_num'] - $v['part_pay_num']) * $v['sale_price'];
                                }
                            }
                            // 已退款，设置铺货订单状态
                            if ($order_lists) {
                                $csoModel->where(['id' => ['in', array_column($order_lists, 'id')]])->save(['status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CANCELED]);
                            }
                            // 返还信用额
                            if ($add_credit > 0) {
                                $this->op_community_credit($user_id, $add_credit, 'add');
                            }

                            $result['status'] = 1;
                            writeFile($log_key . " success");
                        } else {
                            writeFile($log_key . " fail33");
                            $result['status']   = -3;
                            $result['msg']      = '退款失败，请稍后';
                        }
                    } else {
                        writeFile($log_key . " fail22");
                        $result['status']   = -2;
                        $result['msg']      = '系统繁忙，请稍后再试';
                    }
                } else {
                    writeFile($log_key . " fail11");
                    $result['status']   = -1;
                    $result['msg']      = '用户状态异常';
                }
            } else {
                $result['msg'] = '参数错误2';
            }
        } else {
            $result['msg'] = '参数错误1';
        }
        $this->ajaxReturn($result);
    }

    // 领取奖励金
    public function receive_award()
    {
        $cso_id     = I('get.cso_id', 0);
        $user_id    = I('get.user_id', 0);
        $result     = array();
        if ($cso_id && $user_id) {
            $csoModel = D('Yjsh/CommunityStoreOrder');
            $order    = $csoModel->where(['id' => $cso_id, 'status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY, 'award' => ['GT', 0], 'award_status' => 0, 'community_user_id' => $user_id])->find();
            if ($order) {
                $data = [
                    'community_user_id' => $user_id,
                    'cs_id'             => $cso_id,
                    'award'             => $order['award'],
                    'created_at'        => time()
                ];
                // 添加奖励金记录
                $re = M('community_store_award')->add($data);
                if ($re) {
                    // 更新订单数据，设置奖励金为已领取状态
                    $csoModel->where(['id' => $cso_id])->save(['award_status' => 1]);
                    $result['status'] = 1;
                } else {
                    $result['msg'] = '系统繁忙，请稍后重试';
                }
            } else {
                $result['msg'] = '参数错误2';
            }
        } else {
            $result['msg'] = '参数错误1';
        }
        $this->ajaxReturn($result);
    }

    // 我的订单列表
    public function order_list()
    {
        $user_id    = I('get.user_id', 0);
        $pos        = I('get.pos', 0);
        $result     = array();
        if ($user_id) {
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $conf       = $this->get_config();
            $where      = ' cso.community_user_id = ' . $user_id;
            if ($pos == 2) {
                // 待调回
                $start_time = strtotime(date("Y-m-d"));
                $end_time   = $start_time + 24 * 3600;
                $where      .= " and cso.status = " . CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY . " and return_num > 0 and csr.created_at < $end_time and csr.created_at > $start_time";
                $count      = $csoModel
                    ->alias('cso')
                    ->join("__COMMUNITY_STORE_RETURN__ csr on csr.cso_id = cso.id")
                    ->where($where)
                    ->count();
                $page       = $this->page($count, $this->page_size);
                $lists      = $csoModel
                    ->alias('cso')
                    ->join("__COMMUNITY_STORE_RETURN__ csr on csr.cso_id = cso.id")
                    ->join('__PRODUCT__ p on p.id = cso.p_id')
                    ->where($where)
                    ->field('cso.*, p.pre_pic, p.name, p.sale_price, p.market_price, p.cs_max_return_num, p.cs_return_day, p.cs_award_money')
                    ->limit($page->firstRow , $page->listRows)
                    ->order('cso.finish_time desc, cso.created_at desc')
                    ->select();
            } else {
                if ($pos == 0) {
                    // 待付款
                    $where .= " and ( cso.status = " . CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_PAY . " or cso.status = " . CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY . " or cso.status = " . CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_WAIT_PAY . ")";
                } elseif ($pos == 1) {
                    // 待配送
                    $where .= " and cso.status = " . CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND;
                } elseif ($pos == 3) {
                    // 已发货
                    $where .= " and cso.status > " . CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND;
                } else {
                    // 已完成
                    $where .= " and cso.status = " . CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY;
                }
                $count      = $csoModel->alias('cso')->where($where)->count();
                $page       = $this->page($count, $this->page_size);
                $lists      = $csoModel
                    ->alias('cso')
                    ->join('__PRODUCT__ p on p.id = cso.p_id')
                    ->where($where)
                    ->field('cso.*, p.pre_pic, p.name, p.sale_price, p.market_price, p.cs_max_return_num, p.cs_return_day, p.cs_award_money')
                    ->limit($page->firstRow , $page->listRows)
                    ->order('cso.finish_time desc, cso.created_at desc')
                    ->select();
            }
            foreach ($lists as $k => $v) {
                $v['prePic']    = $conf['img_base_url'] . $v['pre_pic'];
                $lists[$k]      = $v;
            }
            $result['status']   = 1;
            $result['pages']    = ceil($count / $this->page_size);
            $result['lists']    = $lists;
        } else {
            $result['msg'] = '参数错误1';
        }
        $this->ajaxReturn($result);
    }

    // 获取订单信息
    // -1       订单已取消，获取该笔订单的所有商品
    // 0        订单未支付，获取该笔订单的所有商品，显示支付按钮
    // 1        订单未配送，获取该笔订单的所有商品，显示退款按钮
    // 2        订单（信用额支付）已送达，未支付实际金额，获取单个商品信息
    // 3        订单（信用额支付）已结算，过了最后回调时间，但未支付，获取单个商品信息，显示支付按钮
    // 4        订单已结算，信用额支付的已经支付了剩余金额，获取单个商品信息
    public function get_order_info()
    {
        $cso_id     = I('get.cso_id', 0);
        $user_id    = I('get.user_id', 0);
        $result     = array();
        if ($cso_id && $user_id) {
            $conf       = $this->get_config();
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $order      = $csoModel->where(['id' => $cso_id])->find();
            if ($order) {
                $show_button    = array('pay_btn' => false, 'refund_btn' => false, 'cancel_btn' => false, 'award_btn' => false, 'go_return' => false, 'go_part_pay' => false, 'pay_expire' => false);
                $where          = ['community_user_id' => $user_id];
                if ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_CANCELED) {
                    // 订单已取消，获取该笔订单的所有商品
                    $where['cso.cso_no']  = $order['cso_no'];
                } elseif ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_PAY) {
                    // 订单未支付，获取该笔订单的所有商品，显示支付按钮
                    $where['cso.cso_no']        = $order['cso_no'];
                    $show_button['pay_btn']     = true;
                    $show_button['cancel_btn']  = true;
                } elseif ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND) {
                    // 订单未配送，获取该笔订单的所有商品，显示退款按钮
                    $where['cso.cso_no'] = $order['cso_no'];
                    $end_time   = strtotime(date("Y-m-d " . $conf ? $conf['group_end_time'] : '23:00:00'));
                    $start_time = strtotime(date("Y-m-d"));
                    if ($start_time < $order['created_at'] && $order['created_at'] < $end_time) {
                        // 当天的可以退款
                        $show_button['refund_btn'] = true;
                    }
                } elseif ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY) {
                    // 订单（信用额支付）已送达，未支付实际金额，获取单个商品信息
                    $where['cso.id']            = $cso_id;
                    $show_button['go_return']   = true;
                    $show_button['go_part_pay'] = true;
                } elseif ($order['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_WAIT_PAY) {
                    // 订单（信用额支付）已结算，过了最后回调时间，但未支付，获取单个商品信息，显示支付按钮
                    $where['cso.id']            = $cso_id;
                    $show_button['pay_expire']  = true;
                } else {
                    // 订单已结算，信用额支付的已经支付了剩余金额，获取单个商品信息
                    $where['cso.id'] = $cso_id;
                    // 领取奖励金按钮
                    if ($order['award'] > 0 && $order['award_status'] == 0) {
                        $show_button['award_btn'] = true;
                    }
                }
                $lists = $csoModel
                    ->alias('cso')
                    ->join('__PRODUCT__ p on p.id = cso.p_id')
                    ->where($where)
                    ->field('cso.*, p.pre_pic, p.name, p.sale_price, p.market_price, p.cs_max_return_num, p.cs_return_day, p.cs_award_money, (SELECT GROUP_CONCAT(cid) as c_ids FROM t_product_category WHERE pid = cso.p_id) as category_ids')
                    ->limit(0)
                    ->select();

                // 需要代采费的商品总件数
                $sg_num     = 0;
                // 订单编号
                $cso_no     = 0;
                // 下单时间
                $created_at = 0;
                // 奖励金
                $award_num  = 0;
                // 支付详情
                $pay_detail = array('total' => 0, 'credit' => 0, 'need_pay' => 0);
                // 个数详情
                $num_detail = array('total' => 0, 'guard' => 0, 'other' => 0);

                foreach ($lists as $k => $v) {
                    $cso_no     = $cso_no ?: $v['cso_no'];
                    $created_at = $created_at ?: date("Y-m-d H:i:s", $v['created_at']);
                    if ($show_button['pay_btn']) {
                        // 未支付订单
                        $pay_detail['total']        = $pay_detail['total'] + $v['total_num'] * $v['sale_price'];
                        $pay_detail['credit']       = $pay_detail['credit'] + $v['protect_num'] * $v['sale_price'];
                        $v['num']                   = $v['total_num'];
                        // 判断是否需要代采费
                        $category_ids   = explode(',', $v['category_ids']);
                        $service_pro    = 1;
                        foreach ($category_ids as $c_id) {
                            if (in_array($c_id, $this->no_service_fee_category)) {
                                $service_pro = 0;
                                break;
                            }
                        }
                        if ($service_pro) {
                            $sg_num = $sg_num + $v['total_num'];
                        }
                    } elseif ($show_button['pay_expire']) {
                        // 支付过期未支付订单
                        $pay_detail['total']        = $pay_detail['total'] + max(0, $v['protect_num'] - $v['part_pay_num']) * $v['sale_price'];
                        $pay_detail['need_pay']     = $pay_detail['need_pay'] + max(0, $v['protect_num'] - $v['part_pay_num']) * $v['sale_price'];
                        $v['num']                   = max(0, $v['protect_num'] - $v['part_pay_num']);
                    } elseif ($show_button['award_btn']) {
                        // 领取奖励金
                        $award_num = $award_num + $v['award'];
                    }
                    // 商品个数前端展示
                    if ($v['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY || $v['status'] == CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_WAIT_PAY) {
                        $v['cart_num'] = max(0, $v['protect_num'] - $v['part_pay_num']);
                    } else {
                        $v['cart_num'] = $v['total_num'];
                    }
                    // 个数明细
                    $num_detail['total']        = $num_detail['total'] + $v['total_num'];
                    $num_detail['guard']        = $num_detail['guard'] + $v['protect_num'];
                    $num_detail['other']        = $num_detail['other'] + $v['other_num'];

                    $v['prePic']        = $conf['img_base_url'] . $v['pre_pic'];
                    $lists[$k]          = $v;
                }
                // 未支付订单
                if ($show_button['pay_btn'] && $pay_detail['total'] < $this->service_fee_start) {
                    $pay_detail['total']        += $sg_num * $this->service_fee;
                    $pay_detail['need_pay']     = $sg_num * $this->service_fee;
                }
                // 保留两位数组
                $pay_detail['total']            = round($pay_detail['total'], 2);
                $pay_detail['credit']           = round($pay_detail['credit'], 2);
                $pay_detail['need_pay']         = round($pay_detail['need_pay'], 2);
                // 返回数据
                $result['status']       = 1;
                $result['lists']        = $lists;
                $result['show_button']  = $show_button;
                $result['pay_detail']   = $pay_detail;
                $result['num_detail']   = $num_detail;
                $result['cso_no']       = $cso_no;
                $result['created_at']   = $created_at;
                $result['award_num']    = round($award_num, 2);
            } else {
                $result['msg'] = '参数错误2';
            }
        } else {
            $result['msg'] = '参数错误1';
        }
        $this->ajaxReturn($result);
    }

    // 获取 可回调/可分批支付 的订单列表
    public function get_process_order_list()
    {
        $user_id    = I('get.user_id', 0);
        $type       = I('get.type', '');    // return or part_pay
        $result     = array();
        if ($user_id && $type) {
            $conf       = $this->get_config();
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            $where      = ['cso.community_user_id' => $user_id, 'cso.return_num' => 0, 'cso.status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY, 'cso.protect_num' => ['GT', 0]];
            $count      = $csoModel->alias('cso')->where($where)->where('protect_num > part_pay_num')->count();
            $page       = $this->page($count, $this->page_size);
            $lists      = $csoModel
                ->alias('cso')
                ->join('__PRODUCT__ p on cso.p_id = p.id')
                ->where($where)
                ->where('protect_num > part_pay_num')
                ->limit($page->firstRow , $page->listRows)
                ->field('cso.*, p.pre_pic, p.name, p.sale_price, p.market_price, p.cs_max_return_num, p.cs_return_day, p.cs_award_money')
                ->select();
            foreach ($lists as $k => $v) {
                if ($type == 'return') {
                    // 回调，列表展示的商品数
                    $v['cart_num'] = 0;
                } else {
                    // 分批支付，列表展示的商品数
                    $v['cart_num'] = max(0, $v['protect_num'] - $v['part_pay_num']);
                }
                $v['max_num']   = max(0, $v['protect_num'] - $v['part_pay_num']);
                $v['prePic']    = $conf['img_base_url'] . $v['pre_pic'];
                $lists[$k]      = $v;
            }
            $result['status']       = 1;
            $result['pages']        = ceil($count / $this->page_size);
            $result['lists']        = $lists;
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 每天23点，将超过最后回调时间的订单，状态改为已结算未支付，在有团长铺货时检查是否有该任务
    public function task_check_expire_order()
    {
        $where = ['status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY, 'last_return_time' => ['LT', time() - 1], 'protect_num' => ['GT', 0]];
        M('community_store_order')->where($where)->save(['status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_WAIT_PAY]);
        $this->ajaxReturn(['status' => 1]);
    }

    // 周期性调整信用额（一周）
    public function task_cycle_change_credit()
    {
        $csoModel   = D('Yjsh/CommunityStoreOrder');
        $cmModel    = M('community');
        $cm_lists   = $cmModel->where(['cs_status' => 2])->field('id, head_uid, old_credit, new_credit, credit')->select();
        list($start, $end) = get_week_start_end();
        foreach ($cm_lists as $k => $v) {
            $total_amount   = 0;
            $return_amount  = 0;
            $order_lists    = $csoModel
                ->alias('cso')
                ->join('__PRODUCT__ p on p.id = cso.p_id')
                ->where(['cso.community_user_id' => $v['head_uid'], 'cso.finish_time' => ['GT', $start], 'cso.finish_time' => ['LT', $end], 'cso.status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY])
                ->field("p.sale_price, cso.total_num, cso.return_num")
                ->select();
            foreach ($order_lists as $v1) {
                $total_amount   = $total_amount + $v1['total_num'] * $v1['sale_price'];
                $return_amount  = $return_amount + $v1['return_num'] * $v1['sale_price'];
            }
            writeFile('task_cycle_change_credit old_credit = ' . $v['new_credit'] . ' community_user_id = ' . $v['head_uid'] . ' total_amount = ' . $total_amount . '  return_amount = ' . $return_amount);
            if ($total_amount > 0) {
                $new_credit = $v['new_credit'] * (1.05 - $return_amount / $total_amount);
                $cmModel->where(['id' => $v['id']])->save(['old_credit' => $v['new_credit'], 'new_credit' => $new_credit]);
            }
        }
        $this->ajaxReturn(['status' => 1]);
    }

    // 确认收货，或者自动将前一天的未收货订单设置为已收货
    // 回调函数
    public function confirm_order()
    {
        $pcbu_ids = I('get.pcbu_ids', '');
        if ($pcbu_ids) {
            $pcbu_ids   = explode(',', $pcbu_ids);
            $csoModel   = D('Yjsh/CommunityStoreOrder');
            foreach ($pcbu_ids as $pcbu_id) {
                // 信用额支付的，状态改成已送达未支付
                $wait_pay_where = [
                    'pay_call_back_url_id'  => $pcbu_id,
                    'status'                => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND,
                    'order_id'              => ['GT', 0],
                    'protect_num'           => ['GT', 0],
                ];
                $csoModel->where($wait_pay_where)->save(['status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY]);
                // 全部用非信用额支付的，状态改成已送达已完成
                $finish_pay_where = [
                    'cso.pay_call_back_url_id'      => $pcbu_id,
                    'cso.status'                    => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND,
                    'cso.order_id'                  => ['GT', 0],
                    'cso.protect_num'               => 0,
                ];
                $op_lists = $csoModel
                    ->alias('cso')
                    ->join('__PRODUCT__ p on cso.p_id = p.id')
                    ->where($finish_pay_where)
                    ->field('cso.*, p.cs_award_money, p.cs_max_return_num')
                    ->limit(0)
                    ->select();
                foreach ($op_lists as $info) {
                    // 修改状态，奖励金数量
                    $data = [
                        'status'        => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY,
                        'award'         => ($info['cs_award_money'] > 0 && $info['cs_max_return_num'] > 0) ? floor(($info['total_num'] - $info['return_num']) / $info['cs_max_return_num']) * $info['cs_award_money'] : 0,
                        'finish_time'   => time(),
                    ];
                    $csoModel->where(['id' => $info['id']])->save($data);
                    // 调整团长对该商品的可铺货数量
                    $this->change_cm_pro_limit($info['community_user_id'], $info['p_id'], $info['cs_max_return_num'], $info['total_num'], $info['return_num']);
                }
            }
        }
        $this->ajaxReturn(['status' => 1]);
    }

    // 操作团长信用额
    private function op_community_credit($user_id, $credit, $op_type) {
        $info                   = M('community')->where(['head_uid' => $user_id])->find();
        $total_no_pay_credit    = $this->get_cm_no_finish_credit($user_id);
        if ($op_type == 'add') {
            $re = M('community')->where(['head_uid' => $user_id])->save(['credit' => max(0, $info['new_credit'] - $total_no_pay_credit)]);
        } else {
            $re = M('community')->where(['head_uid' => $user_id, 'credit' => ['GT', 0]])->save(['credit' => ['exp', "credit - " . $credit]]);
        }
        writeFile('op_community_credit  user_id = ' . $user_id . " credit = $credit total_no_pay_credit = $total_no_pay_credit op_type = $op_type  old_credit = " . $info['credit']);
        return $re;
    }

    // 计算最后可回调时间
    private function calc_last_return_time($return_day = 0) {
        $config     = $this->get_config();
        $end_time   = $config ? $config['group_end_time'] : "23:00:00";
        return strtotime(date("Y-m-d $end_time", strtotime("+$return_day day")));
    }

    private function get_config()
    {
        $redis  = Redis::getinstance();
        $key    = "Yjsh_config";
        $re     = $redis->get($key);
        if ($re) {
            return $re;
        } else {
            $info = M('config')->where(['id' => 2])->find();
            if (!$info) {
                writeFile("GroupBuy get config error!!!!");
            } else {
                $redis->set($key, $info, 24 * 60 * 60);
            }
            return $info ?: [];
        }
    }

    // 调整团长对商品的可铺货数量
    private function change_cm_pro_limit($user_id, $p_id, $cs_max_return_num, $total_num, $return_num) {
        $last_info = M('community_store_limit')->where(['community_user_id' => $user_id, 'p_id' => $p_id])->order('created_at desc')->find();
        if ($return_num == 0) {
            // 0 回调率, 上涨1的可回调数量
            if ($last_info) {
                $new_return_num = min($cs_max_return_num, $last_info['new_guard_num'] + 1);
                if ($new_return_num != $last_info['new_guard_num']) {
                    $data = [
                        'community_user_id' => $user_id,
                        'p_id'              => $p_id,
                        'org_guard_num'     => $last_info['new_guard_num'],
                        'new_guard_num'     => $new_return_num,
                        'change_type'       => CommunityStoreLimitModel::CSG_NUM_CHANGE_TYPE_SALE_ALL,
                        'change_reason'     => '',
                        'created_at'        => time(),
                    ];
                    M('community_store_limit')->add($data);
                }
            }
        } else {
            // 有回调的情况
            $new_temp1 = max(0, $cs_max_return_num - $return_num);      // 根据本次回调数量，计算的下次最高可回调数
            if ($total_num == $return_num) {
                // 100% 回调率
                $new_return_num = 0;
            } elseif ($return_num * 2 > $total_num) {
                // 50% 回调率以上
                $count = M('community_store_order')
                    ->where(['community_user_id' => $user_id, 'status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY])
                    ->where('return_num * 2 > total_num')
                    ->count();
                if ($count >= 2) {
                    $new_return_num = 0;
                } else {
                    $new_return_num = min($cs_max_return_num, $new_temp1, max(0, $last_info ? $last_info['new_guard_num'] - 1 : $cs_max_return_num - 1));
                }
            } else {
                $new_return_num = min($cs_max_return_num, $new_temp1, max(0, $last_info ? $last_info['new_guard_num'] - 1 : $cs_max_return_num - 1));
            }
            $data = [
                'community_user_id' => $user_id,
                'p_id'              => $p_id,
                'org_guard_num'     => $last_info ? $last_info['new_guard_num'] : $cs_max_return_num,
                'new_guard_num'     => $new_return_num,
                'change_type'       => CommunityStoreLimitModel::CSG_NUM_CHANGE_TYPE_RETURN,
                'change_reason'     => 'return_num=' . $return_num,
                'created_at'        => time(),
            ];
            M('community_store_limit')->add($data);
        }
    }

    // 获取团长没有结算的订单的信用额总额
    private function get_cm_no_finish_credit($user_id = 0) {
        $total_no_pay_credit = 0;
        if ($user_id) {
            $order_lists = M('community_store_order')
                ->alias('cso')
                ->join('__PRODUCT__ p on p.id = cso.p_id')
                ->where(['cso.community_user_id' => $user_id, 'cso.protect_num' => ['GT', 0], 'cso.status' => ['in', [CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND, CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY, CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_WAIT_PAY]]])
                ->field("p.sale_price, cso.protect_num, cso.part_pay_num")
                ->select();
            foreach ($order_lists as $v) {
                $total_no_pay_credit = $total_no_pay_credit + max(0, $v['protect_num'] - $v['part_pay_num']) * $v['sale_price'];
            }
        }
        return $total_no_pay_credit;
    }

    // 获取商品库存
    private function get_product_stocks($p_ids = array()) {
        if ($p_ids) {
            $url    = "https://yjsh.rixins.cn/admin/api/getProductStockByIds?ids=" . implode(',', $p_ids); // 返回顺序与请求顺序相同
            $re     = curl_requestion($url, [], 'GET', 60);
            $p_s    = [];
            if ($re['status']) {
                $re     = json_decode($re['data'], true);
                $stocks = explode(',', $re['data']);
                foreach ($p_ids as $k => $p_id) {
                    $p_s[$p_id] = (int)($stocks[$k]);
                }
            }
            return $p_s;
        }
        return [];
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////永鲜生 - 司机端部分/////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // 查询司机今天是否有送货任务
    public function is_today_send()
    {
        $result     = array();
        $driver_id  = I('get.driver_id', 0); // 司机id
        if ($driver_id) {
            $user_info      = M('user')->where(['id' => $driver_id])->find();
            $driver_info    = M('driver')->where(['uid' => $driver_id, 'status' => ['GT', 1]])->find();
            if ($user_info && $user_info['type'] == 3 && $driver_info) {
                // 检查今天是否有送货任务
                $need_send = M('line')->where(['driver_id' => $driver_info['id'], 'send_time' => date("Y-m-d")])->find();
                $result['status']       = 1;
                $result['need_send']    = $need_send ? 1 : 0;
            } else {
                $result['msg'] = '身份信息有误';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 获取今天需送货的店长列表
    public function get_send_community_list()
    {
        $result     = array();
        $driver_id  = I('get.driver_id', 0); // 司机id
        if ($driver_id) {
            $user_info      = M('user')->where(['id' => $driver_id])->find();
            $driver_info    = M('driver')->where(['uid' => $driver_id, 'status' => ['GT', 1]])->find();
            if ($user_info && $user_info['type'] == 3 && $driver_info) {
                // 检查今天是否有送货任务
                $need_send = M('line')->where(['driver_id' => $driver_info['id'], 'send_time' => date("Y-m-d")])->find();
                if ($need_send) {
                    $lists = M('line_community')
                        ->alias('lc')
                        ->join('__COMMUNITY__ c on lc.commu_id = c.id')
                        ->where(['lc.line_id' => $need_send['id']])
                        ->field('lc.status, c.id, c.head_uid, c.name, c.address, c.mobile')
                        ->limit(0)
                        ->order('lc.sort desc, c.id asc')
                        ->select();

                    $result['status']       = 1;
                    $result['lists']        = $lists;
                    $result['line_id']      = $need_send['id'];
                    $result['groupon_id']   = $need_send['groupon_id'];
                    $result['is_ready']     = $need_send['status'] >= 1 ? 1 : 0;
                } else {
                    $result['msg'] = '今天没有送货任务';
                }
            } else {
                $result['msg'] = '身份信息有误';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 开始送货接口，用于状态维护
    public function ready_to_send()
    {
        $result     = array();
        $driver_id  = I('get.driver_id', 0); // 司机id
        $line_id    = I('get.line_id', 0); // 线路id
        if ($driver_id && $line_id) {
            $user_info      = M('user')->where(['id' => $driver_id])->find();
            $driver_info    = M('driver')->where(['uid' => $driver_id, 'status' => ['GT', 1]])->find();
            if ($user_info && $user_info['type'] == 3 && $driver_info) {
                // 更新状态
                $need_send = M('line')->where(['driver_id' => $driver_info['id'], 'send_time' => date("Y-m-d"), 'id' => $line_id])->find();
                if ($need_send) {
                    if ($need_send['status'] <= 0) {
                        M('line')->where(['id' => $line_id])->save(['status' => 1]);
                    }
                    // 将所有店长的送货状态都改成已出发
                    M('line_community')->where(['line_id' => $line_id, 'status' => 0])->save(['status' => 1]);
                    // 数据返回
                    $result['status'] = 1;
                } else {
                    $result['msg'] = '数据错误，请联系技术 . 。o O o 。.';
                }
            } else {
                $result['msg'] = '身份信息有误';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 获取店长订单详情
    public function get_community_order_list()
    {
        $result         = array();
        $cu_id          = I('get.cu_id', 0); // 店长id
        $driver_id      = I('get.driver_id', 0); // 司机id
        $groupon_id     = I('get.groupon_id', 0); // 出货信息表id （groupon表）
        if ($cu_id && $groupon_id) {
            $cm_info        = M('community')->where(['head_uid' => $cu_id, 'cs_status' => 2])->find();
            $driver_info    = M('driver')->where(['uid' => $driver_id, 'status' => ['GT', 1]])->find();
            $line_info      = M('line')->where(['driver_id' => $driver_info['id'], 'groupon_id' => $groupon_id])->find();
            $lc_info        = M('line_community')->where(['line_id' => $line_info['id'], 'commu_id' => $cm_info['id']])->find();
            $groupon_info   = M('groupon')->where(['id' => $groupon_id])->find();
            // 用户信息
            $cm_user_info           = M('user')->where(['id' => $cu_id])->field('avatar_url, nick_name')->find();
            $cm_info['avatar_url']  = $cm_user_info['avatar_url'];
            $cm_info['nick_name']   = $cm_user_info['nick_name'];
            if ($groupon_info && $line_info && $lc_info && $driver_info && $cm_info) {
                if ($lc_info['status'] > 1) {
                    // 已送货
                    // 总金额
                    $total_amount = $created_at =  0;
                    // 实际送货信息
                    $confirm_lists = M('community_store_confirm')
                        ->alias('csc')
                        ->join("__PRODUCT__ p on p.id = csc.p_id")
                        ->join("__PACK__ pc on p.pack_id = pc.id", 'left')
                        ->where(['csc.community_user_id' => $cu_id, 'csc.groupon_id' => $groupon_id])
                        ->field("p.id, p.name, p.sale_price, csc.amount, csc.num, csc.created_at, p.pack_id, p.pack_num, pc.name as pk_name, pc.amount as pk_amount")
                        ->order('csc.cso_id asc')
                        ->select();
                    $pk_info = array();
                    foreach ($confirm_lists as $k => $v) {
                        if (isset($pk_info[$v['pack_id']])) {
                            $pk_info[$v['pack_id']]['leave_num'] += $v['num'] * $v['pack_num'];
                        } else {
                            if ($v['pack_id']) {
                                $pk_info[$v['pack_id']] = array('name' => $v['pk_name'], 'leave_num' => $v['num'] * $v['pack_num'], 'return_num' => 0);
                            }
                        }
                        $total_amount += $v['amount'] + $v['num'] * $v['pack_num'] * $v['pk_amount'];
                        $created_at = $created_at ?: $v['created_at'];
                        $v['total_num'] = $v['num'];
                        $confirm_lists[$k] = $v;
                    }
                    // 收回的框
                    $return_pk_info = M('community_store_return_package')->where(['community_user_id' => $cu_id, 'groupon_id' => $groupon_id])->find();
                    if ($return_pk_info) {
                        $return_pk = json_decode($return_pk_info['return_package'], true);
                        foreach ($return_pk as $k => $v) {
                            // 框的钱
                            $pk = M('pack')->where(['id' => $v['package_id']])->field("name, amount")->find();
                            $total_amount -= $v['num'] * $pk['amount'];

                            // 框的信息
                            if (isset($pk_info[$v['package_id']])) {
                                $pk_info[$v['package_id']]['return_num'] += $v['num'];
                            } else {
                                $pk_info[$v['package_id']] = array('name' => $pk['name'], 'leave_num' => 0, 'return_num' => $v['num']);
                            }
                        }
                    }
                    // 返回数据
                    $result['status']       = 1;
                    $result['order_list']   = array_merge($confirm_lists);
                    $result['pk_info']      = array_merge($pk_info);
                    $result['total_amount'] = $total_amount;
                    $result['cm_info']      = $cm_info;
                    $result['send_time']    = $created_at;
                    $result['send_status']  = 1;
                } else {
                    // 未送货
                    $conf       = $this->get_config();
                    // 商品总数, 待收回的框的总数, 总金额
                    $total_goods_num = $total_old_pk_num = 0;
                    // 留下的框
                    $leave_pk   = array();
                    // 查询
                    $csoModel   = D('Yjsh/CommunityStoreOrder');
                    $where      = [
                        'cso.community_user_id' => $cu_id,
                        'cso.created_at'        => [['EGT', strtotime($groupon_info['start_time'])], ['ELT', strtotime($groupon_info['end_time'])], 'AND'],
                    ];
                    // 店长本次订单列表
                    $cso_lists  = $csoModel
                        ->alias('cso')
                        ->join('__PRODUCT__ p on cso.p_id = p.id')
                        ->join('__PACK__ pk on p.pack_id = pk.id', 'left')
                        ->where($where)
                        ->field('cso.*, p.pre_pic, p.name, p.sale_price, p.standard, p.pack_id, p.pack_num, pk.name as pk_name, pk.amount as pk_amount')
                        ->limit(0)
                        ->order('cso.id asc')
                        ->select();
                    foreach ($cso_lists as $k => $v) {
                        if ($v['pack_id'] > 0) {
                            if (array_key_exists($v['pack_id'], $leave_pk)) {
                                $leave_pk[$v['pack_id']]['num'] += $v['pack_num'] * $v['total_num'];
                            } else {
                                $leave_pk[$v['pack_id']] = array('name' => $v['pk_name'], 'num' => $v['pack_num'] * $v['total_num'], 'package_id' => $v['pack_id'], 'pk_amount' => $v['pk_amount']);
                            }
                        }
                        if ($v['standard']) {
                            // 标品
                            $amount = max(0, $v['total_num'] - $v['protect_num']) * $v['sale_price'];
                        } else {
                            // 非标品
                            $amount = -1;
                        }
                        $v['amount']    =  round($amount, 2);
                        $v['pre_pic']   = $conf['img_base_url'] . $v['pre_pic'];
                        $v['weight']    = 0;
                        $v['max_num']   = $v['total_num'];
                        $v['show_edit'] = 0;
                        $total_goods_num += $v['total_num'];
                        $cso_lists[$k]  = $v;
                    }
                    // 店长手里的框的记录
                    $sql            = "select csp.package_id, csp.num, p.name, p.amount as pk_amount from t_community_store_package csp inner join t_pack p on p.id = csp.package_id where csp.id in (( select max(id) from t_community_store_package where community_user_id = " . $cu_id . " group by package_id ))";
                    $old_pk_lists   = M('community_store_package')->query($sql);
                    $old_pk_lists   = array_column($old_pk_lists, NULL, 'package_id');
                    // 框的总信息
                    $pk_info = array();
                    foreach ($leave_pk as $pk_id => $v) {
                        $pk_info[$pk_id] = array('name' => $v['name'], 'leave_num' => $v['num'], 'max_old_num' => 0, 'return_num' => 0, 'package_id' => $pk_id, 'pk_amount' => $v['pk_amount']);
                    }
                    foreach ($old_pk_lists as $pk_id => $v) {
                        $total_old_pk_num += $v['num'];
                        if (isset($pk_info[$pk_id])) {
                            $pk_info[$pk_id]['max_old_num'] += $v['num'];
                        } else {
                            $pk_info[$pk_id] = array('name' => $v['name'], 'leave_num' => 0, 'max_old_num' => $v['num'], 'return_num' => 0, 'package_id' => $pk_id, 'pk_amount' => $v['pk_amount']);
                        }
                    }
                    array_merge(sort($pk_info));
                    // 店长信息
                    $cm_info                = M('community')->where(['head_uid' => $cu_id])->find();
                    $cm_user_info           = M('user')->where(['id' => $cu_id])->field('avatar_url, nick_name')->find();
                    $cm_info['avatar_url']  = $cm_user_info['avatar_url'];
                    $cm_info['nick_name']   = $cm_user_info['nick_name'];

                    // 返回结果
                    $result['status']       = 1;
                    $result['lists']        = array_merge($cso_lists);
                    $result['pk_info']      = $pk_info;
                    $result['groupon_id']   = $groupon_id;
                    $result['cm_info']      = $cm_info;
                    $result['goods_num']    = $total_goods_num;
                    $result['old_pk_num']   = $total_old_pk_num;
                    $result['send_status']  = 0;
                }
            } else {
                $result['msg'] = '参数错误~';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }

    // 订单确认送达
    public function confirm_send()
    {
        $result         = array();
        $cu_id          = I('get.cu_id', 0);            // 店长id
        $total_amount   = I('get.total_amount', 0);     // 总金额
        $driver_id      = I('get.driver_id', 0);        // 司机id
        $groupon_id     = I('get.groupon_id', 0);       // 出货信息表id （groupon表）
        $order_info     = $_POST['order_info'];         // 订单信息
        $return_pk      = $_POST['return_pk'];          // 回收框信息
        $user_info      = M('user')->where(['id' => $driver_id])->find();
        $driver_info    = M('driver')->where(['uid' => $driver_id, 'status' => ['GT', 1]])->find();
        if ($cu_id && $order_info && $user_info && $user_info['type'] == 3 && $driver_info) {
            $order_info = json_decode($order_info, true); // [{"cso_id":1,"num":1,"amount":3.2,"weight":4.5},...]
            $return_pk  = json_decode($return_pk, true); // [{"package_id":1,"num":1},...]
            if ($order_info) {
                $order_info     = array_column($order_info, NULL, 'cso_id');
                $return_pk      = $return_pk ? array_column($return_pk, NULL, 'package_id') : [];
                $cm_info        = M('community')->where(['head_uid' => $cu_id])->find();
                // 1. 根据信息，算出需要支付的金额
                $groupon_info = M('line')
                    ->alias("l")
                    ->join("__GROUPON__ g on g.id = l.groupon_id")
                    ->join("__LINE_COMMUNITY__ lc on l.id = lc.line_id")
                    ->where(['l.groupon_id' => $groupon_id, 'l.driver_id' => $driver_info['id'], 'lc.commu_id' => $cm_info['id'], 'l.send_time' => date("Y-m-d"), 'l.status' => ['LT', 2], 'lc.status' => ['LT', 2]])
                    ->field("g.*")
                    ->find();
                writeFile('444444444');
                writeFile($groupon_info);
                if ($groupon_info) {
                    // 查询
                    $csoModel   = D('Yjsh/CommunityStoreOrder');
                    $where      = [
                        'cso.community_user_id' => $cu_id,
                        'cso.created_at'        => [['EGT', strtotime($groupon_info['start_time'])], ['ELT', strtotime($groupon_info['end_time'])], 'AND'],
                    ];
                    // 店长本次订单列表
                    $cso_lists = $csoModel
                        ->alias('cso')
                        ->join('__PRODUCT__ p on cso.p_id = p.id')
                        ->join('__PACK__ pk on p.pack_id = pk.id', 'left')
                        ->where($where)
                        ->field('cso.*, p.pre_pic, p.name, p.sale_price, p.standard, p.pack_id, p.pack_num, pk.name as pk_name, pk.amount as pk_amount')
                        ->limit(0)
                        ->order('cso.id asc')
                        ->select();
                    $cso_lists = array_column($cso_lists, NULL, 'id');
                    if (count($cso_lists) == count($order_info)) {
                        $calc_amount    = 0; // 实际应收金额
                        $confirm_data   = array(); // 确认订单，账单信息
                        $cs_pk_data     = array(); // 店长的框的统计
                        foreach ($cso_lists as $cso_id => $v) {
                            if (array_key_exists($cso_id, $order_info)) {
                                if ($v['total_num'] >= $order_info[$cso_id]['num']) {
                                    if ($v['standard']) {
                                        // 标品
                                        $need_amount = $order_info[$cso_id]['num'] * $v['sale_price'];
                                    } else {
                                        // 非标品
                                        $need_amount = $order_info[$cso_id]['weight'] * $v['sale_price'];
                                    }
                                    if ($order_info[$cso_id]['amount'] >= $need_amount) {
                                        // 商品应收金额
                                        $calc_amount += $need_amount;
                                        // 框应收的金额
                                        $calc_amount += $order_info[$cso_id]['num'] * $v['pack_num'] * $v['pk_amount'];
                                        // 账单信息
                                        $confirm = array(
                                            'community_user_id' => $v['community_user_id'],
                                            'cso_id'            => $v['id'],
                                            'p_id'              => $v['p_id'],
                                            'num'               => $order_info[$cso_id]['num'],
                                            'weight'            => $order_info[$cso_id]['weight'],
                                            'amount'            => $order_info[$cso_id]['amount'],
                                            'groupon_id'        => $groupon_id,
                                            'created_at'        => time(),
                                        );
                                        $confirm_data[] = $confirm;
                                        // 框的统计信息
                                        if ($v['pack_id'] > 0) {
                                            if (isset($cs_pk_data[$v['pack_id']])) {
                                                $cs_pk_data[$v['pack_id']]['num'] += $order_info[$cso_id]['num'] * $v['pack_num'];
                                            } else {
                                                $cs_pk_data[$v['pack_id']] = array(
                                                    'num'               => $order_info[$cso_id]['num'] * $v['pack_num'],
                                                    'groupon_id'        => $groupon_id,
                                                    'package_id'        => $v['pack_id'],
                                                    'community_user_id' => $cu_id,
                                                    'created_at'        => time(),
                                                );
                                            }
                                        }
                                    } else {
                                        $result['msg'] = '<' . $v['name'] . '> 收取金额不足';
                                        break;
                                    }
                                } else {
                                    $result['msg'] = '<' . $v['name'] . '> 超出订货数量';
                                    break;
                                }
                            } else {
                                $result['msg'] = '还有未确认的商品~';
                                break;
                            }
                        }
                        // 退回的框
                        if ($return_pk) {
                            // 检查店长手里的框
                            $sql            = "select package_id, num from t_community_store_package where id in (( select max(id) from t_community_store_package where community_user_id = " . $cu_id . " group by package_id ))";
                            $old_pk_lists   = M('community_store_package')->query($sql);
                            $old_pk_lists   = array_column($old_pk_lists, NULL, 'package_id');
                            // 查询框的价格
                            $pk_info = M('pack')->where(['id' => ['in', array_column($return_pk, 'package_id')]])->field('id, amount')->select();
                            $pk_info = array_column($pk_info, NULL, 'id');
                            foreach ($return_pk as $pk_id => $v) {
                                if (array_key_exists($pk_id, $old_pk_lists)) {
                                    if ($old_pk_lists[$pk_id]['num'] >= $v['num']) {
                                        // 减去收回框的钱
                                        $calc_amount -= $v['num'] * $pk_info[$pk_id]['amount'];
                                        // 框的统计信息
                                        if (isset($cs_pk_data[$pk_id])) {
                                            $cs_pk_data[$pk_id]['num'] -= $v['num'];
                                        } else {
                                            $cs_pk_data[$pk_id] = array(
                                                'num'               => -$v['num'],
                                                'groupon_id'        => $groupon_id,
                                                'package_id'        => $pk_id,
                                                'community_user_id' => $cu_id,
                                                'created_at'        => time(),
                                            );
                                        }
                                    } else {
                                        $result['msg'] = '框回收数量超出';
                                        break;
                                    }
                                } else {
                                    $result['msg'] = '框回收数据异常';
                                    break;
                                }
                            }
                        }
                        if (!isset($result['msg'])) {
                            // 对比前端发来的金额，确认是否正确
                            $calc_amount = round($calc_amount, 2);
                            writeFile('11111111111');
                            writeFile($calc_amount);
                            writeFile($cs_pk_data);
                            if ($total_amount >= $calc_amount) {
                                // 统计店长手里的框的数量
                                $insert_pk_data = array();
                                foreach ($cs_pk_data as $pk_id => $v) {
                                    if (isset($old_pk_lists[$pk_id])) {
                                        $new_num = $old_pk_lists[$pk_id]['num'] + $v['num'];
                                        if ($new_num >= 0) {
                                            $v['num'] = $new_num;
                                            $insert_pk_data[] = $v;
                                        } else {
                                            $result['msg'] = '框回收数量超出!';
                                            break;
                                        }
                                    } else {
                                        if ($v['num'] > 0) {
                                            $insert_pk_data[] = $v;
                                        } else {
                                            $result['msg'] = '框回收数量超出~';
                                            break;
                                        }
                                    }
                                }
                                if (!isset($result['msg'])) {
                                    // 更新 community_store_package 表的数据，维护店长手里的框
                                    writeFile('222222222');
                                    writeFile($insert_pk_data);
                                    if ($insert_pk_data) {
                                        M('community_store_package')->addAll($insert_pk_data);
                                    }

                                    // 修改 community_store_order 表状态
                                    M('community_store_order')
                                        ->where(['id' => ['in', array_column($cso_lists, 'id')], 'status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND, 'protect_num' => 0])
                                        ->save(['status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_CLOSE_HAS_PAY]);
                                    M('community_store_order')
                                        ->where(['id' => ['in', array_column($cso_lists, 'id')], 'status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_WAIT_SEND, 'protect_num' => ['GT', 0]])
                                        ->save(['status' => CommunityStoreOrderModel::CSG_ORDER_STATUS_HAS_SEND_WAIT_PAY]);

                                    // 添加 community_store_confirm 表的数据
                                    if ($confirm_data) {
                                        M('community_store_confirm')->addAll($confirm_data);
                                    }

                                    // 修改 line_community 表的状态
                                    $line_model = M('line');
                                    $lc_model   = M('line_community');
                                    $line       = $line_model->where(['driver_id' => $driver_info['id'], 'groupon_id' => $groupon_id])->find();
                                    $commu_info = M('community')->where(['head_uid' => $cu_id])->find();
                                    writeFile('3333333333');
                                    writeFile($line);
                                    if ($line && $commu_info) {
                                        // 更新单个店长的送货状态
                                        $lc_model->where(['line_id' => $line['id'], 'commu_id' => $commu_info['id']])->save(['status' => 2]);
                                        // 检查是否送货今天的送货任务已完成
                                        $all_count      = $lc_model->where(['line_id' => $line['id']])->count();
                                        $finish_count   = $lc_model->where(['line_id' => $line['id'], 'status' => 2])->count();
                                        if ($finish_count >= $all_count) {
                                            $line_model->where(['id' => $line['id']])->save(['status' => 2]);
                                        }
                                    }
                                    // 记录收回框的log
                                    if ($return_pk) {
                                        M('community_store_return_package')->add(array(
                                           'community_user_id'  => $cu_id,
                                            'groupon_id'        => $groupon_id,
                                            'return_package'    => json_encode(array_merge($return_pk)),
                                            'created_at'        => time(),
                                        ));
                                    }
                                    // 数据返回
                                    $result['status'] = 1;
                                }
                            } else {
                                $result['msg'] = '结算金额小于应付金额，请重新核实订单';
                            }
                        }
                    } else {
                        $result['msg'] = '还有未确认的商品';
                    }
                } else {
                    $result['msg'] = '数据错误，请联系技术';
                }
            } else {
                $result['msg'] = '参数错误~';
            }
        } else {
            $result['msg'] = '参数错误';
        }
        $this->ajaxReturn($result);
    }
}


